// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        aliveDur: 0.5,
        rate: 1,
        nextTime: 0.0,
        enemyPrefab: {
            default: null,
            type: cc.Prefab,
        }
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start() {
        this.nodePool = new cc.NodePool();
        let initCount = 50;
        for (let i = 0; i < initCount; ++i) {
            let enemy = cc.instantiate(this.enemyPrefab); // 创建节点
            this.nodePool.put(enemy); // 通过 putInPool 接口放入对象池
        }
    },

    update(dt) {
        if (this.nextTime <= 0) {
            this.addTail();
            this.nextTime = this.rate;
        }
        this.nextTime -= dt;
    },

    addTail() {
        let enemy = null;
        if (this.nodePool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            enemy = this.nodePool.get();
        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
            enemy = cc.instantiate(this.enemyPrefab);
        }
        if(cc.zsb.player){
            this.targetNode = cc.zsb.player.node;
            enemy.parent = this.targetNode.parent;
            enemy.position = this.targetNode.position;
            enemy.opacity = 255;
            var action = cc.fadeOut(this.aliveDur);
            var action2 = cc.callFunc(function(enemy){
                this.nodePool.put(enemy);
            }, this);
            enemy.runAction(cc.sequence(action, action2));
        }
      
    }
});
